package qj.concurrent;

/**
 * Servant Association
 * Created by QuanLA
 * Date: Mar 31, 2006
 * Time: 8:59:59 AM
 */
public class Servant {

    /**
     * Define a good behaviour of a concurrent when process a task.
     * @param task
     */
    public static void serveTask(ServantTask task) {
        try {
            if (!task.isCancelled()) {
                for (int i = 0; i < task.getListeners().size(); i++)
                    ((TaskProgressListenable) task.getListeners().get(i)).taskStart(task);
                task.run();
            }
        } catch (Throwable e) {
            if (task.getListeners().size() > 0)
                for (int i = 0; i < task.getListeners().size(); i++)
                    ((TaskProgressListenable) task.getListeners().get(i)).taskThrowed(task, e);
            else
            	e.printStackTrace();//***
        } finally {
            if (task.getListeners().size() > 0)
                for (int i = 0; i < task.getListeners().size(); i++)
                    ((TaskProgressListenable) task.getListeners().get(i)).taskDone(task);
        }

    }
}
